package icu.makka.yygh.msm.controller;

import icu.makka.yygh.msm.service.MsmService;
import icu.makka.yygh.msm.service.impl.MsmServiceImpl;
import icu.makka.yygh.msm.utils.RandomUtil;
import icu.makka.yygh.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@Api(tags = "发送短信接口")
@RequestMapping("/api/msm")
public class MsmApiController {

    @Autowired
    private MsmServiceImpl msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 发送手机验证码
     * @param phone
     * @return
     */
    @ApiOperation(value = "发送手机验证码")
    @GetMapping("/send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        log.info("发送手机验证码到{}", phone);

        //从redis获取验证码，如果获取到，返回ok
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        //如果获取不到，则生成4位验证码
        code = RandomUtil.getFourBitRandom();
        //通过整合短信服务，将验证码发送给用户
        boolean isSend = msmService.send(phone, code);
        log.info("isSend={}, 为true, 则发送成功", isSend);
        if (isSend) {
            //发送成功，则将验证码存入redis，并设置有效期
            redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
            return Result.ok();
        } else {
            //发送失败
            return Result.fail("短信发送失败");
        }

    }
}
